package communication.hall
{
	import com.netease.protobuf.Message;
	
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.utils.ByteArray;
	import flash.utils.Timer;
	
	import communication.ProtoFactory;
	import communication.SocketConnected;


	public class HallSocket extends SocketConnected
	{
		/**
		 * 处理断线重连 
		 */		
		private var timer:Timer = new Timer(15000);
		
		private static var _instance:HallSocket;
		
		public static function init():void
		{
			_instance = new HallSocket(GlobalData.lobbyServerArray);
		}

		public static function get instance():HallSocket
		{
			return _instance;
		}

		/**
		 * 大厅数据发送者 
		 */
		private function get hallMsgSender():HallMsgSender
		{
			return HallMsgSender.instance;
		}

		private var msgProcesser:HallMsgProcesser = HallMsgProcesser.getInstance();
		
		public function HallSocket(serverArray:Array)
		{
			super(serverArray);
			timer.addEventListener(TimerEvent.TIMER,onTimer);
			timer.start();
		}

		private var _authRequest:Message = null;

		public function set authRequest(authRequest:Message):void
		{
			_authRequest = authRequest;
		}

		override protected function connectionComplete():void
		{
			logger("Hall Socket connection Complete..");
			if (_authRequest != null)
			{
				hallMsgSender.sendSessionCert(_authRequest);
			}
		}

		override protected function connectFailed():void
		{
			logger("Hall Socket connection failed..");
		}
		
		/**
		 * Override to implement different socket reconnectSuccess function
		 */
		override protected function reconnectSuccess():void
		{
			logger("Hall Socket reconnect success..");
			if (_authRequest != null)
			{
				hallMsgSender.sendSessionCert(_authRequest);
			}
		}

		override protected function dispatchMessage(messageId:uint, data:ByteArray):void
		{
			ProtoFactory.getHallProto().Decode(messageId, data, msgProcesser);
		}
		
		/**
		 * 处理断线重连
		 */
		private function onTimer(event:Event):void
		{
			if(hasConnected() == false)
			{
				connect();
			}
		}

	}
}
